﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SalesSys.Comm.DAL;

namespace SalesSys.DAL.Base
{


    #region MapBase


    /// <summary>
    /// 抽象映射基类，只实现默认表名映射
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class BaseMap<T> : BaseMapToCfg<T>
        where T : class, IDbEntity
    {
        public abstract string TablePrefix { get; }

        public virtual string GetTableName()
        {
            return TablePrefix + typeof (T).Name;
        }

        public BaseMap()
        {
            ToTable(GetTableName());
        }
    }

    /// <summary>
    /// 映射基础的id，及id生成方法，表名
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="TID"></typeparam>
    public abstract class BaseMap<T, TID> : BaseMap<T>
        where T : DbEntityBase<TID>
        //where TID:struct
    {
        public BaseMap()
        {
            ToTable(GetTableName());
            HasKey(x => x.Id);
            //使用默认策略：int自增，guid手动
            //Property(x => x.Id);
        }
    }


    public abstract class BaseTreeMap<T, TID> : BaseMap<T, TID>
        where T : TreeEntity<TID, T>
        where TID : struct
    {
        public BaseTreeMap()
        {
            HasMany(x => x.Children).WithOptional(x => x.Parent).HasForeignKey(x => x.ParentId);
        }
    }

    public abstract class BaseTimestampMap<T, TID> : BaseMap<T, TID>
        where T : TimestampEntity<TID>
        where TID : struct
    {
        public BaseTimestampMap()
        {
            Property(x => x.RowVersion).IsRowVersion();
        }
    }

    #endregion

    #region IMap

    [InheritedExport()]
    public interface ICustomRegMapCfg
    {
        void RegCfg(ConfigurationRegistrar reg);
    }

    public abstract class BaseMapToCfg<T> : EntityTypeConfiguration<T>, ICustomRegMapCfg where T : class, IDbEntity
    {

        public void RegCfg(ConfigurationRegistrar reg)
        {
            reg.Add(this);
        }
    }

    public class EFAutoMapCfg
    {
        public static void LoadCustomRegMapCfg(ConfigurationRegistrar reg)
        {
            AssemblyCatalog ass = new AssemblyCatalog(typeof (WXEFRepository<>).Assembly);
            CompositionContainer container = new CompositionContainer(ass);
            var maps = container.GetExportedValues<ICustomRegMapCfg>();
            foreach (var item in maps)
            {
                item.RegCfg(reg);
            }
        }
    }

    #endregion
}
